const express = require('express')
const Router = express.Router()
const query = require('./db')

module.exports = Router

/**
 * 初始化消息推送(获取推送给 我 的消息)
 */
Router.get('/messagePushing', async (req, res) => {
    try {
        let { user_id } = req.query
        // let messagePushingListData = await query(`select * from message join article on message.message_to_user_id=article.article_author_id join user on message.message_from_user_id=user.user_id where message_id=${message_id}`)
        let messagePushingData = await query(`select * from message join article on message.message_article_id=article.article_id join user on message.message_from_user_id=user.user_id where message_to_user_id=${user_id} and message_from_user_id<>message_to_user_id order by message_read asc, message_time desc`)
        let notReadCount = await query(`select * from message where message_read='0'`)
        if (messagePushingData.length === 0) {
            res.send({
                code: 400,
                msg: '当前用户没有新的推送消息',
            })
            return
        }
        res.send({
            code: 200,
            msg: '获取当前用户推送消息成功',
            data: {
                messagePushingData,
                notReadCount: notReadCount.length
            }

        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})


/**
 * 消息已读
 */
Router.get('/readMessage', async (req, res) => {
    try {
        let { message_id } = req.query
        let data = await query(`update message set message_read='1' where message_id=${message_id}`)
        res.send({
            code: 200,
            msg: '修改消息状态成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

/**
 * 全部已读
 */
Router.get('/allRead', async (req, res) => {
    try {
        let { user_id } = req.query
        let data = await query(`update message set message_read='1' where message_to_user_id=${user_id}`)
        res.send({
            code: 200,
            msg: '修改全部消息状态成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})

/**
 * 清空已读消息
 */
Router.get('/clearRead', async (req, res) => {
    try {
        let { user_id } = req.query
        let data = await query(`delete from message where message_to_user_id=${user_id} and message_read='1'`)
        res.send({
            code: 200,
            msg: '清空已读消息成功',
            data
        })
    } catch (error) {
        console.log(error);
        res.send({
            code: 0,
            error
        })
    }
})


